package com.neusoft.tyut.tyutcat.core;

import com.neusoft.tyut.tyutcat.http.HttpServletRequest;
import com.neusoft.tyut.tyutcat.servlet.Servlet;
import com.neusoft.tyut.tyutcat.servlet.factory.ServletFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Objects;

public class CatThread extends  Thread {
    private Socket socket;
    public CatThread(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        InputStream is = null;
        BufferedReader  reader = null;
        int index = 0 ;
        try {
            is = socket.getInputStream();
            reader =new BufferedReader( new InputStreamReader(is));
            String msg =  null ;
            HttpServletRequest request = new HttpServletRequest();
            while ( (msg = reader.readLine() )!=null)  {
                index++;
                if (index == 1){
                    String [] ss  =  msg.split(" ");
                    request.setMethod(ss[0]);
                    String[] s2s =    ss[1].split("/");
                    request.setWebName(s2s[0] );

                    int i = s2s[2].indexOf("?");
                    if (i ==-1){
                        request.setUrl( s2s[2] );
                    }else {
                        request.setUrl( s2s[2].substring(0 , s2s[2].indexOf("?")));
                    }


                    /**
                     * TODO :  解析参数
                     */
                }
                else {
//                    Connection: keep-alive
                    if (  msg ==null || msg.trim().equals("") ||  msg.trim().length() <2 ){

                    }else {
                        String[] ss = msg.split(": ");
                        if (ss.length == 2){
                            request.addHeader(ss[0], ss[1] );
                        }

                    }

                }

            }
            Servlet servlet = ServletFactory.getServlet(request.getUrl());
            servlet.service(request);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } finally {
            try {
                if (!Objects.isNull(reader)) reader.close();
                if (!Objects.isNull(is)) is.close();
                this.socket.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }


    }
}
